<template>
	<view class="wrap">

		<view class="header">
			<view class="header-inner">
				<view class="back-png" @click="backPage">
					<image class="header-image" src="@/static/images/arrow-left.svg" mode="aspectFill"></image>
				</view>
				<view class="title">
					拍照上传
				</view>
				<view></view>
			</view>
		</view>

		<view class="danjuleixing">
			<view class="name-type">
				单据类型
			</view>
			<view class="type-value">
				<u--input v-model="code" placeholder="请输入单据号" :customStyle="{'height':'50px'}" color="#3460F9"
					inputAlign="right" border="false" clearable></u--input>
				<!-- GLD20221223-A001 -->
			</view>
		</view>

		<view class="picture-title">
			照片上传
		</view>

		<view class="upload-wrap">
			<view class="unit-pic" @click="previewImage(index)" v-for="(item, index) in fileList" :key="index">
				<image class="item-image" :src="item.url" mode="aspectFill"></image>
				<view @click.stop="itemCheck(item)" :class="['checkbox-unit',item.checked?'checked':'']"></view>
				<image @click.stop="itemCheck(item)" :class="['fi-br-check',item.checked?'checked':'']"
					src="@/static/images/fi-br-check.svg" mode="aspectFill"></image>
				<!-- <view class="u-delete-icon" @click="itemCheck(item)">
					<u-icon name="close" size="20" color="#ffffff"></u-icon>
				</view> -->
			</view>


			<view class="up-btn">
				<u-upload :custom-btn="true" :show-upload-list="showUploadList" @afterRead="afterRead" name="1" multiple
					:maxCount="25" :auto-upload="false">
					<image class="upload-add" src="@/static/images/upload-add.svg"></image>
				</u-upload>
			</view>


		</view>


		<view class="up-footer">
			<u-row customStyle="margin-bottom: 10px;display:flex;justify-content: space-between;padding:0px 15px;">

				<template v-if="isMangerImg">
					<u-col span="5.8">
						<u-button style="border-radius: 12px;background: #3461FD;color: white;" text="取消"
							@click="cancelAll"></u-button>
					</u-col>
					<u-col span="5.8">
						<u-button style="border-radius: 12px;" text="删除" @click="deleteItem"></u-button>
					</u-col>
				</template>

				<template v-else>
					<u-col span="12">
						<u-button style="border-radius: 12px;background: #3461FD;color: white;" text="确定上传"
							@click="submit"></u-button>
					</u-col>
				</template>

			</u-row>
		</view>
	</view>
</template>

<script>
	import {
		scanCode
	} from "@/mixin/scan-code/scan-code.js";
	import upload from "@/utils/upload";
	import {
		uploadImg
	} from "@/api/port-area.js"

	export default {
		mixins: [scanCode], //混入文件
		data() {
			return {
				code: "",
				showUploadList: false,
				uUpload: {}, // 组件实例
				// {
				// 	url: 'https://5b0988e595225.cdn.sohucs.com/images/20190124/60e5c9d2286549d1b4bbaaba17cb6e31.jpeg',
				// 	checked:true,
				// 	// status: 'uploading',
				// }, 
				fileList: [],
			}
		},
		onReady() {
			// 得到整个组件对象，内部图片列表变量为"lists"
			this.uUpload = this.$refs.uUpload;
		},
		computed: {
			isMangerImg() {
				return this.fileList.some(item => {
					return item.checked == true;
				})
			}
		},
		onShow() {},
		methods: {
			backPage() {
				uni.navigateBack({
					delta: 1
				});
			},
			deleteItem() {
				let list = this.fileList.filter(item => {
					return !item.checked
				})
				this.fileList = list
			},
			cancelAll() {
				for (var i = 0; i < this.fileList.length; i++) {
					let item = this.fileList[i];
					this.$set(this.fileList[i], "checked", false)
				}
			},
			itemCheck(item) {
				var check = item.checked
				this.$set(item, 'checked', !check)
			},
			async uploadImg(lists) {
				let _this = this;
				let uid = this.code + new Date().getTime();
				let pAll = [];
				for (let i = 0; i < lists.length; i++) {
					let item = lists[i]
					let p = new Promise(async (resolve, reject) => {
						console.log("item.url", item.url)
						let picid = await uploadImg({
							url: '/common/api/v1/attachment/upload', //仅为示例，非真实的接口地址
							filePath: item.url,
							formData: {
								bizUid: uid,
								bizType: "receipt_attachment"
							}
						})
						// console.log('res', res)
						if (picid) {
							resolve(picid)
						} else {
							reject(-1)
						}
					})

					console.log('ppp', p)
					pAll.push(p);
				}
				Promise.all(pAll).then((val) => {
					console.log('全部完成', val);
					_this.$modal.msgSuccess("上传成功")
					_this.reset();
					// 相关操作
				}).catch((err) => {
					console.log("err", err)
				});

			},
			reset() {
				this.code = "";
				this.fileList = [];
			},
			submit() {
				if (!this.code) {
					this.$modal.msgError('请输入单据号');
					return false;
				}
				if (!this.fileList.length) {
					this.$modal.msgError('请选择图片');
					return false;
				}
				console.log('fileList', JSON.stringify(this.fileList));
				this.uploadImg(this.fileList)
			},
			//移动图片到指定文件夹
			copyFileToDirectory(oldPath, newDirectory) {
				const filename = Date.now() + '.jpg'
				return new Promise((resolve, reject) => {
					plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
						// fs.root是根目录操作对象DirectoryEntry  
						fs.root.getDirectory(newDirectory, {
							create: true
						}, function(entry1) {
							console.log('新目录----' + entry1.fullPath);
							plus.io.resolveLocalFileSystemURL(oldPath,
								function(entry2) {
									console.log('旧文件---' + entry2.fullPath);
									entry2.copyTo(entry1, filename,
										function(res) {
											console.log('移动成功', res.fullPath);
											resolve('file://' + res.fullPath)
										},
										function(e) {
											console.log('内层移动失败' + JSON.stringify(e))
											reject('内层移动失败' + JSON.stringify(e))
										})
								},
								function(e) {
									console.log('移动失败' + JSON.stringify(e))
									reject('移动失败' + JSON.stringify(e))
								})
						}, e => {
							console.log('外层操作失败' + JSON.stringify(e))
							reject('外层操作失败' + JSON.stringify(e))
						});
					})
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList`].splice(event.index, 1)
			}, // 新增图片
			async afterRead(event) {
				// file:///storage/emulated/0/DCIM/Camera/
				console.log('event.name', event)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				console.log('lists', lists)
				let fileListLen = this[`fileList`].length
				lists.map((item) => {
					this[`fileList`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const oldPath = lists[i].url
					const newLocalDirectory = 'file:///storage/emulated/0/DCIM/HUAYOU/12345/'
					let newLocalPath = await this.copyFileToDirectory(oldPath, newLocalDirectory)
					console.log('newLocalPath', newLocalPath)

					const result = await this.uploadFilePromise(newLocalPath)
					let item = this[`fileList`][fileListLen]
					this[`fileList`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}

			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					resolve(url)
				})
			},
			previewImage(index) {
				uni.previewImage({
					urls: this.fileList.map(item => item.url), // 图片列表
					current: index, // 当前显示图片的索引
					indicator: 'number' // 图片指示器样式，默认为圆点
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	/deep/ .u-upload__button {
		width: 100% !important;
		height: 100% !important;
	}

	.wrap {
		width: 100%;
		height: calc(100vh);
		padding-top: 270rpx;
		overflow-y: scroll;
		background: var(--additional-colors-white, #FFF);
	}

	.header {
		width: 100%;
		height: 270rpx;
		flex-shrink: 0;
		border-radius: 0px 0px 60rpx 60rpx;
		background: #3461FD;
		position: fixed;
		top: 0;
		z-index: 999;
		padding-top: 120rpx;

		.header-inner {
			display: flex;
			justify-content: space-between;
			padding: 0 50rpx;
			align-items: center;

			.title {
				color: #FFF;
				text-align: center;
				font-size: 36rpx;
				font-family: PingFang SC;
				font-style: normal;
				font-weight: 800;
				line-height: 52rpx;
				letter-spacing: 0.09px;
			}

			.back-png {
				width: 100rpx;
				height: 100rpx;
				// padding: 24px;
				border-radius: 24rpx;
				text-align: center;
				line-height: 48rpx;
				background-image: url("@/static/images/back-bg.svg");
				background-size: 100rpx 100rpx;
				background-repeat: no-repeat;
				display: flex;
				justify-content: center;
				align-items: center;

				.header-image {
					width: 48rpx;
					height: 48rpx;
				}
			}

			.scan-png {
				width: 48rpx;
				height: 48rpx;
				border-radius: 24rpx;
				text-align: center;
				line-height: 48rpx;

				.header-image {
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	.up-footer {
		position: fixed;
		bottom: 0px;
		width: 100vw;
	}

	.picture-title {
		color: #000;
		font-size: 36rpx;
		font-family: PingFang SC;
		font-style: normal;
		font-weight: 600;
		line-height: 70rpx;
		padding: 20rpx;
	}

	.upload-wrap {
		display: flex;
		flex-wrap: wrap;
		padding: 10rpx 30rpx;
		margin-bottom: 100rpx;

		.unit-pic {
			flex: 31.3%;
			margin: 5rpx;
			height: 288rpx;
			flex-grow: 0;
			// flex-shrink: 0;
			border-radius: 32rpx;
			background: url(<path-to-image>), lightgray 50% / cover no-repeat;
			box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.08);
			overflow: hidden;
			position: relative;

			.item-image {
				width: 100%;
				height: 100%;
			}
		}

		.up-btn {
			flex: 30%;
			margin: 10rpx;
			height: 288rpx;
			flex-grow: 0;
			box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.08);
			border-radius: 32rpx;
			border: 1px dashed #3461FD;
			background: #FFF;
			text-align: center;
			display: flex;
			justify-content: center;
			overflow: hidden;

			/deep/ .u-upload__wrap {
				justify-content: center;
				align-content: center;
			}

			.upload-add {
				width: 160rpx;
				height: 160rpx;
				// margin: 100rpx auto;
			}

			/deep/ .u-upload__wrap>uni-view {
				display: flex;
				align-items: center;
			}
		}
	}

	.u-upload__wrap {
		/deep/ &>uni-view {
			width: 100%;
		}
	}

	.danjuleixing {
		width: calc(100vw - 40rpx);
		height: 100rpx;
		flex-shrink: 0;
		border-radius: 20rpx;
		background: #FFF;
		box-shadow: 0px 0px 50rpx 0px rgba(0, 0, 0, 0.10);
		margin: 16rpx auto;
		display: flex;
		padding: 0 30rpx;
		align-items: center;
		justify-content: space-between;
		line-height: 100rpx;

		.name-type {
			color: var(--gray-3, #828282);
			text-align: left;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-style: normal;
			font-weight: 600;
			line-height: normal;
			width: 240rpx;
			flex-shrink: 0;
		}

		.type-value {
			color: #1278FF;
			text-align: center;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-style: normal;
			font-weight: 600;
			line-height: normal;
		}
	}

	.checkbox-unit {
		width: 30rpx;
		height: 30rpx;
		border: 2rpx solid white;
		position: absolute;
		right: 15rpx;
		bottom: 15rpx;
		border-radius: 3rpx;
	}

	.checkbox-unit.checked {
		background-color: blue;
	}

	.fi-br-check.checked {
		width: 26rpx;
		height: 26rpx;
		position: absolute;
		right: 18rpx;
		bottom: 18rpx;
		border-radius: 3rpx;
		padding: 4rpx;
	}
</style>